<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业实现低成本数字化转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\energy;

use think\App;
use app\controller\property\Base;
use app\validate\energy\EnergyUsersValidate;
use app\common\repositories\users\UsersRepository;
use app\common\repositories\energy\EnergyUsersRepository;
use app\common\repositories\energy\EnergyMeterRepository;


class EnergyUsers extends Base
{
    protected $repository;

    public function __construct(App $app, EnergyUsersRepository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
        $this->assign([
            'addAuth' => property_auth('propertyEnergyUsersAdd'),
            'editAuth' => property_auth('propertyEnergyUsersEdit'),
            'delAuth' => property_auth('propertyEnergyUsersDel'),
            'detailAuth' => property_auth('propertyEnergyUsersDetail'),
        ]);
    }

    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'energy_id' => '',
                'keywords' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $data = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $data['list'], 'count' => $data['count']]);
        }
        return $this->fetch('energy/users/list');
    }


    /**
     * 批量充值
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-03-15 21:02
     */
    public function add(EnergyMeterRepository $repository)
    {
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'id' => '',
                'mobile' => '',
                'remark' => '',
            ]);
            $param['status'] = 1;
            $param['is_main'] = 1;
            validate(EnergyUsersValidate::class)->scene('add')->check($param);
            $ids = array_filter(explode(',', $param['id']));
            $usersRepository = app()->make(UsersRepository::class);
            $userInfo = $usersRepository->getInfoByMobile($param['mobile']);
            if (!$userInfo) {
                return $this->error($param['mobile'] . ' 用户不存在');
            }
            unset($param['id']);
            unset($param['mobile']);
            $param['user_id'] = $userInfo['id'];
            $meterlist = $repository->getSearch([])
                ->where('id', 'in', $ids)
                ->where('plan_type', 'in', '2,3')
                ->field('id,property_id,energy_type,plan_type')
                ->select()->toArray();
            if ($meterlist) {
                foreach ($meterlist as $v) {
                    if (isset($v) && $v['id'] > 0 && ($v['plan_type'] == 2 || $v['status'] == 3)) {
                        $param['energy_id'] = $v['id'];
                        $param['property_id'] = $v['property_id'];
                        $param['energy_type'] = $v['energy_type'];
                        $this->repository->addInfo($this->request->propertyId, $param, $this->request->userId);
                    }
                }
                return $this->success('设备分享成功');
            } else {
                return $this->error('失败设备分享');
            }
        } else {
            $id = $this->request->param('id');
            $ids = array_filter(explode(',', $id));
            $rechargelist = $repository->getSearch([])
                ->where('id', 'in', $ids)
                ->where('plan_type', 'in', '2,3')
                ->field('id,energy_no,energy_name,energy_type,plan_type,balance,read_time')
                ->select()->toArray();
            $this->assign([
                'rechargeData' => $rechargelist,
            ]);
            return $this->fetch('energy/users/add');
        }
    }


    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->get($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'remark' => '',
                'status' => '',
            ]);
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                return $this->error('网络错误');
            }
        } else {
            return $this->fetch('energy/users/edit', [
                'info' => $info,
            ]);
        }
    }

    public function del()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->userId);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            return $this->error('网络失败');
        }
    }


}